package com.aerors.DataProcess;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.gdal.gdal.gdal;

/**
 * 将tiff格式更改为cogeotiff格式并建立影像金字塔
 * 
 * @author wx
 *
 */
public class CoGeoTIFFBuilder {
	private static final String rootPath = "C:\\data\\shapes\\矢量";
	private static final String outPath = "C:\\data\\cogeo";
	private static final List<String> errorList = new ArrayList<>();

	private static final String cogeotiffBuildTemplate = "gdal_translate %s %s -co TILED=YES -co COMPRESS=DEFLATE -co COPY_SRC_OVERVIEWS=YES -co BLOCKXSIZE=512 -co BLOCKYSIZE=512 --config GDAL_TIFF_OVR_BLOCKSIZE 512 -co BIGTIFF=YES";
	private static final String ovrBuildTemplate = "gdaladdo -r average %s 2 4 8 16 32 64 128";
	static {
		gdal.AllRegister();
	}

	public static void main(String[] args) throws IOException, InterruptedException {
		File srcFile = new File("C:\\data\\rawgeotiff\\3857t.tif");
		CoGeoTIFFBuilder builder = new CoGeoTIFFBuilder();
		builder.buildOVR(srcFile);
		builder.buildCogeoTIFF(srcFile);
	}

	public String buildCogeoTIFF(File f) throws IOException, InterruptedException {
		String fName = f.getName();
		String newFileName = fName.substring(0, fName.lastIndexOf(".") + 1) + "cogeo."
				+ fName.substring(fName.lastIndexOf(".") + 1, fName.length());
		String outFilePath = outPath + File.separator + newFileName;
//		System.out.println("newFileName:" + newFileName);
//		System.out.println("outFilePath:" + outFilePath);
		String command = String.format(cogeotiffBuildTemplate, f.getAbsolutePath(), outFilePath);
		this.execCommand(command);
		return outFilePath;
	}

	public void buildOVR(File f) {
		String command = String.format(ovrBuildTemplate, f.getAbsolutePath());
		this.execCommand(command);
	}

	public void execCommand(String command) {
		Process p = null;
		try {
			System.out.println("command:" + command);
			p = Runtime.getRuntime().exec(command);
			String s = null;
			BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(p.getInputStream()));
			while ((s = bufferedReader.readLine()) != null) {
				System.out.println(s);
			}
			p.waitFor();
		} catch (Exception e) {
			System.out.println(e.getCause() + ";" + e.getMessage());
		}finally {
			p.destroy();
		}
	}
}
